|
1
|
|
|
'use strict' |
|
2
|
|
|
|
|
3
|
|
|
module.exports = (input, callback) => { |
|
4
|
|
|
const mqtt = require('mqtt') |
|
5
|
|
|
const configuration = require('./configuration') |
|
6
|
|
|
const validate = require('./validate') |
|
7
|
|
|
let error = null |
|
8
|
|
|
let output = null |
|
9
|
|
|
|
|
10
|
|
|
validate.sourceConfiguration(input, (validatedInput, thrownError) => { |
|
11
|
|
|
input = validatedInput |
|
12
|
|
|
error = thrownError |
|
13
|
|
|
}) |
|
14
|
|
|
validate.paramConfiguration(input, (validatedInput, thrownError) => { |
|
15
|
|
|
input = validatedInput |
|
16
|
|
|
error = thrownError |
|
17
|
|
|
}) |
|
18
|
|
|
|
|
19
|
|
|
// Send MQTT |
|
20
|
|
|
if ( !error ) { |
|
21
|
|
|
let configurationMqtt = configuration.mqtt(input) |
|
22
|
|
|
let client = mqtt.connect(input.source.url, configurationMqtt) |
|
23
|
|
|
|
|
24
|
|
|
client.on('connect', () => { |
|
25
|
|
|
client.subscribe(input.source.topic, (errorConnection) => { |
|
26
|
|
|
if ( !errorConnection ) { |
|
27
|
|
|
client.publish(input.source.topic, input.params.payload, { |
|
28
|
|
|
qos: input.params.qos, |
|
29
|
|
|
retain: false |
|
30
|
|
|
}) |
|
31
|
|
|
} else { |
|
32
|
|
|
error = errorConnection |
|
33
|
|
|
} |
|
34
|
|
|
}) |
|
35
|
|
|
}) |
|
36
|
|
|
|
|
37
|
|
|
client.on('message', (topic, message) => { |
|
38
|
|
|
output = { |
|
39
|
|
|
'version': {'ref': 'output'}, |
|
40
|
|
|
'metadata': [ |
|
41
|
|
|
{'name': 'message', 'value': input.params.payload.toString()}, |
|
42
|
|
|
{'name': 'receivedMessage', 'value': message.toString()}, |
|
43
|
|
|
{'name': 'qos', 'value': input.params.qos.toString()}, |
|
44
|
|
|
{'name': 'timestamp', 'value': Date.now().toString()}, |
|
45
|
|
|
{'name': 'topic', 'value': topic} |
|
46
|
|
|
] |
|
47
|
|
|
} |
|
48
|
|
|
client.end() |
|
49
|
|
|
}) |
|
50
|
|
|
callback(error, output) |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|